<?php

namespace App\Http\Controllers\Backend;


use App\Models\ArticleComment;
use App\Models\News;
use App\Models\NewsCate;
use App\Models\NewsDesc;
use App\Models\NewsTopic;
use App\Models\SiteCate;
use App\Models\Topic;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class NewsController extends BaseController
{
    // 新闻文章

    protected $list_cache = true;

    public function initialize()
    {
        parent::initialize();

        $this->model = 'news';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 返回列表数据
    public function lists()
    {
        $cate_id = $this->getData('cate_id', 0, 'intval');
        $where   = [];
        $page    = $this->page;
        $rows    = $this->rows;
        $model   = $this->checkModel($this->model);
        if($model === false){
            return $this->error($this->error);
        }

        // 模型 和 查询
        if($cate_id){
            $result = $model->isCache($this->list_cache)->listCatePage($where, $page, $rows, "shl_news.id DESC");
        } else{
            $result = $model->isCache($this->list_cache)->listPage($where, $page, $rows, "id DESC");
        }
        // 用户头像，粉丝数量，关注数量，金币数
        if($result['list']){
            $userDb    = new User();
            $desDb     = new NewsDesc();
            $cateDb    = new NewsCate();
            $topicDb   = new NewsTopic();
            $topicMain = new Topic();
            $cateMain  = new SiteCate();
            $types     = $this->userType(); // 认证类型
            // 用户
            $uids  = array_column($result['list'], 'uid');
            $users = $userDb->isCache(true)->getListInIds($uids);
            $users = array_column($users, null, 'id');
            // 详情
            $newsIds = array_column($result['list'], 'id');
            $descs   = $desDb->isCache(true)->getListInIds($newsIds, '*', 'news_id');
            // 话题
            $ntList   = $topicDb->whereIn('news_id', $newsIds)->get()->toArray();
            $topicIds = array_column($ntList, 'topic_id');
            $topics   = $topicMain->isCache(true)->getListInIds($topicIds);
            $ntList2  = $ntList;
            $ntList   = [];
            foreach($ntList2 as $_nt){
                $news_id = $_nt['news_id'];
                // 整理
                $ntList[$news_id][] = $_nt['topic_id'];
            }

            // 栏目
            $ncList  = $cateDb->whereIn('news_id', $newsIds)->get()->toArray();
            $cateIds = array_column($ncList, 'cate_id');
            $cates   = $cateMain->isCache(true)->getListInIds($cateIds);
            $ncList2 = $ncList;
            $ncList  = [];
            foreach($ncList2 as $_nc){
                $news_id = $_nc['news_id'];
                // 整理
                $ncList[$news_id][] = $_nc['cate_id'];
            }

            // 整理
            foreach($result['list'] as $key => $item){
                $_uid    = $item['uid'];
                $_newsId = $item['id'];

                // 整理用户
                $_user = $users[$_uid] ?? [];
                if($_user){
                    // $_user['apply_type'] = $types[$_user['apply_type']]['name'] ?? '';
                    $_user['apply_type'] = $_user['is_apply'] == 1 ? ($types[$_user['apply_type']]['name'] ?? '') : '';
                    $_user['head_img']   = $this->getHeadImg($_user['head_img'] ?? '');
                } else{
                    $_user = (object)[];
                }
                // 整理话题
                $_topicIds = $ntList[$_newsId] ?? [];
                $_topics   = [];
                foreach($_topicIds as $_topicId){
                    if(empty($topics[$_topicId])){
                        continue;
                    }
                    $_topics[] = $topics[$_topicId];
                }

                // 整理栏目
                $_cateIds = $ncList[$_newsId] ?? [];
                $_cates   = [];
                $comm     = $cate_name = '';
                foreach($_cateIds as $_cateId){
                    if(empty($cates[$_cateId])){
                        continue;
                    }
                    $_cates[]  = $cates[$_cateId];
                    $cate_name .= $comm.$cates[$_cateId]['title'];
                    $comm      = ',';
                }

                // 整理内容(列表需要去除图片)
                /*if($item['description']){
                    $content = $item['description'];
                } else{
                    $content = $descs[$_newsId]['content'] ?? '';
                    $content = $this->makeListShow($content);
                }*/
                $content = $descs[$_newsId]['content'] ?? '';
                $content = $this->makeListShow($content, 'news');

                // 整理
                $result['list'][$key]['topic_ids']  = $_topicIds;
                $result['list'][$key]['topics']     = $_topics;
                $result['list'][$key]['is_propose'] = in_array(1, $_cateIds) ? 1 : 0;
                $result['list'][$key]['cate_ids']   = $_cateIds;
                $result['list'][$key]['cates']      = $_cates;
                $result['list'][$key]['cate_name']  = $cate_name;
                $result['list'][$key]['content']    = $content;
                $result['list'][$key]['user']       = $_user;
                $result['list'][$key]['images']     = $this->makeFullFile($item['images']);  // 图片
            }
        }

        return $this->success($result);
    }

    // 置顶操作
    public function toTop()
    {
        $is_top = $this->getData("is_top", 0, 'intval');
        $ids    = $this->getData("ids", [], 'is_array');
        $this->throwReturn(empty($ids), '请选择需要修改的数据！');
        $this->throwReturn(!in_array($is_top, [0, 1]), '请选择正确置顶状态！');
        $this->throwReturn(count($ids) != count($ids, 1), '请选择正确id数据！');

        // 查询数据
        $model = new News();
        $lists = $model->isCache(true)->getListInIds($ids);
        if(empty($lists)){
            return $this->error('你要操作的数据不存在！！');
        }

        $_ids = array_column($lists, 'id');
        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $model->whereIn('id', $_ids)->update(['is_top' => $is_top]);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 缓存操作
        $model->deleteCacheList($lists);
        $model->deleteCacheShow(['id' => $_ids, 'is_top' => $is_top]);

        return $this->success();
    }

    // 设置到推荐
    public function toRecommend()
    {
        $ids = $this->getData("ids", [], 'is_array');
        $this->throwReturn(empty($ids), '请选择需要修改的数据！');
        $this->throwReturn(count($ids) != count($ids, 1), '请选择正确id数据！');

        // 查询数据
        $model = new News();
        $lists = $model->isCache(true)->getListInIds($ids);
        if(empty($lists)){
            return $this->error('你要操作的数据不存在！！');
        }

        // 查询这些文章中没有被推荐的文章
        $nCateDb = new NewsCate();
        $noInIds = [];
        foreach($lists as $item){
            $ncInfo = $nCateDb->oneFind(['cate_id' => 1, 'news_id' => $item['id']]);
            if(empty($ncInfo)){
                $noInIds[] = $item['id'];
            }
        }
        if(empty($noInIds)){
            return $this->error('你要操作的数据都已经被推荐！！');
        }
        $addCate = [];
        foreach($noInIds as $id){
            $addCate[] = ['cate_id' => 1, 'news_id' => $id, 'status' => 1, 'ctime' => LARAVEL_TIME,];
        }


        // 设置推荐的栏目
        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $nCateDb->insert($addCate);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 缓存操作
        $model->deleteCacheList($lists);
        $model->deleteCacheShow(['id' => $ids]);

        return $this->success();
    }

    // 取消推荐
    public function cancelRecommend()
    {
        $ids = $this->getData("ids", [], 'is_array');
        $this->throwReturn(empty($ids), '请选择需要修改的数据！');
        $this->throwReturn(count($ids) != count($ids, 1), '请选择正确id数据！');

        // 查询数据
        $model = new News();
        $lists = $model->isCache(true)->getListInIds($ids);
        if(empty($lists)){
            return $this->error('你要操作的数据不存在！！');
        }

        // 设置推荐的栏目
        $nCateDb = new NewsCate();
        DB::beginTransaction();
        try{
            foreach($lists as $item){
                $nCateDb->where(['cate_id' => 1, 'news_id' => $item['id']])->delete();
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 缓存操作
        $model->deleteCacheList($lists);
        $model->deleteCacheShow(['id' => $ids]);

        return $this->success();
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->softDelete($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 删除（软删除）
    public function delComment()
    {
        $ids = $this->getData('ids', [], 'is_array');
        $this->throwIf(empty($ids), '请指定删除记录!');
        $this->throwIf(count($ids) != count($ids, 1), '指定删除记录参数错误!');
        // 其他条件
        $news_id = $this->getData('news_id', 0, 'intval');
        $where   = ['channel' => 'news', 'article_id' => $news_id];
        $this->throwIf(empty($news_id), '请指定新闻文章编号!');

        $comment = new ArticleComment();
        $result  = $comment->isCache(true)->softDelete($where, $ids);
        $this->throwIf($result === false, $comment->getError());

        return $this->success();
    }

    // 查找
    public function show()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = [['id', '=', $this->id], ['verify', '=', 1]];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());

        // 查找用户信息
        if($info['uid']){
            $uid    = $info['uid'];
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            // $user   = $userDb->isCache(true)->getListInIds([$uid]);
            $user = $userDb->isCache(true)->getOneById($uid);
            if($user){
                // $user               = $user[$uid];
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
            }
            $info['user'] = $user;
        }

        return $this->success($info);
    }

    // 快讯的评论
    public function comment()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');
        $where   = ['article_id' => $this->id, 'channel' => 'news', 'verify' => 1]; // 'pid' => 0,
        $comment = new ArticleComment();
        $result  = $comment->listPage($where, $this->page, $this->rows);
        if($result['list']){
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_info = $users[$_uid] ?? [];
                if($_info){
                    $_info['head_img']   = $this->getHeadImg($_info['head_img'] ?? '');
                    $_info['apply_type'] = $_info['is_apply'] == 1 ? ($types[$_info['apply_type']]['name'] ?? '') : '';
                    // $_info['apply_type'] = $types[$_info['apply_type']]['name'] ?? '';
                }

                // 整理
                $result['list'][$key]['user']       = $_info;
                $result['list'][$key]['apply_type'] = $_info['is_apply'] == 1 ? ($types[$item['apply_type']]['name'] ?? '') : '';
                // $result['list'][$key]['apply_type'] = $types[$item['apply_type']]['name'] ?? '';
            }
        }

        return $this->success($result);
    }

}


